<?php

namespace App\V3\Api\Services;

use App\V3\Api\Models\MaterielClassModel;
use App\V3\Api\Models\MaterielsTypeModel;
use Illuminate\Support\Facades\DB;

class MaterielClassService
{
    /**
     * 商品分类列表
     * @param $mainId 主账号id
     * @param $data['pageSize'] 页面大小即显示条数
     * @param $data['currentPage'] 当前页
     * @param $data['keyword'] 关键词
     * @param $data['class_id'] id标识
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/3 14:52
     * @return mixed
     */
    static public function index($mainId, $data)
    {
        $condition = [];
        $condition1 = [];
        if(!empty($data['materiel_class_id'])) {
            $condition['b.id'] = ['EQ' => $data['materiel_class_id']];
            $condition1['materiel_class_id'] = ['EQ' => $data['materiel_class_id']];
        }

        $keyword = empty($data['keyword'])?'':$data['keyword'];

        if(!empty($condition) || $keyword != '') {
            $result = SELF::withSearch($mainId, $data, $condition, $condition1, $keyword);
        }
        else {
            $result = SELF::withoutSearch($mainId, $data);
        }

        return $result;
    }

    static public function withSearch($parentId, $data, $condition, $condition1, $keyword)
    {
        $typeInfo = MaterielClassModel::getMaterielAndClassInfo($parentId, $condition, $keyword, $data);

        $firstClass = [];
        $secondClass = [];
        foreach($typeInfo as $k => $v) {
            $firstClass[] = $v['f_id'];
            $secondClass[] = $v['s_id'];
        }

        return MaterielClassModel::select(
            'id',
            'class_name',
            'class_no',
        )
            ->from('materiel_class')
            ->where('main_id', $parentId)
            ->with('nextClass', function($query) use ($secondClass, $condition1, $keyword) {
                $query->select(
                    'id',
                    'class_name',
                    'class_no',
                    'parent_id'
                )
                    ->where('delete_flag', 0)
                    ->with('nextType', function($query) use ($condition1, $keyword) {
                        $query->select(
                            'id',
                            'materiel_name',
                            'type_name',
                            'materiel_img',
                            'materiel_no',
                            'materiel_class_id',
                            'remark'
                        )
                            ->where($condition1)
                            ->where('delete_flag', 0)
                            ->orWhere(function($query) use ($keyword) {
                                $query->orWhere('materiel_name', 'LIKE', '%'.$keyword.'%');
                                $query->orWhere('type_name', 'LIKE', '%'.$keyword.'%');
                                $query->orWhere('materiel_no', 'LIKE', '%'.$keyword.'%');
                            });
                    })
                    ->whereIn('id', array_unique($secondClass));
            })
            ->where('parent_id', 0)
            ->where('delete_flag', 0)
            ->whereIn('id', array_unique($firstClass))
            ->orderBy('id', 'asc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
    }

    static public function withoutSearch($parentId, $data)
    {
        $info = MaterielClassModel::select(
            'id',
            'class_name',
            'class_no',
        )
            ->from('materiel_class')
            ->where('main_id', $parentId)
            ->with('nextClass', function($query) {
                $query->select(
                    'id',
                    'class_name',
                    'class_no',
                    'parent_id'
                )
                    ->where('delete_flag', 0)
                    ->with('nextType', function($query) {
                        $query->select(
                            'id',
                            'materiel_name',
                            'type_name',
                            'materiel_img',
                            'materiel_no',
                            'materiel_class_id',
                            'remark'
                        )
                            ->where('delete_flag', 0);
                    });
            })
            ->where('parent_id', 0)
            ->where('delete_flag', 0)
            ->orderBy('id', 'asc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        return $info;
    }

    //物料商品分类下拉列表
    static public function select($mainId)
    {
        return MaterielClassModel::select(
            'id', 'class_name', 'class_no'
        )->with('nextClass', function($query) {
            $query->select(
                'id', 'class_name', 'class_no', 'parent_id'
            )->where('delete_flag', 0)->orderBy('id', 'desc');
        })->where([
            'main_id' => $mainId,
            'delete_flag' => 0,
            'parent_id' => 0
        ])->orderBy('id', 'desc')->get();
    }

    //新建商品分类
    static public function add($mainId, $data)
    {
        //type->0:一级分类;1:二级分类;
        if($data['type']) {
            if($data['parent_id'] == 0) {
                return ['code' => 1, 'msg' => '请选择一级商品分类'];
            }

            $checkNoInfo = MaterielClassModel::where([
                'parent_id' =>  $data['parent_id'],
                'class_no' => $data['class_no'],
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->first();

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  $data['parent_id'],
                'class_name' => $data['class_name'],
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->first();

            if(!empty($checkNoInfo)) {
                return ['code' => 1, 'msg' => '分类编号`'.$data['class_no'].'`已存在'];
            }

            if(!empty($checkNameInfo)) {
                return ['code' => 1, 'msg' => '分类`'.$data['class_name'].'`已存在'];
            }
        }
        else {
            $checkNoInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_no' => $data['class_no'],
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->first();

            if(!empty($checkNoInfo)) {
                return ['code' => 1, 'msg' => '分类编号`'.$data['class_no'].'`已存在'];
            }

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_name' => $data['class_name'],
                'main_id' => $mainId,
                'delete_flag' => 0
            ])->first();

            if(!empty($checkNameInfo)) {
                return ['code' => 1, 'msg' => '分类`'.$data['class_name'].'`已存在'];
            }
        }

        unset($data['type']);

        $insertId = MaterielClassModel::insertGetId($data);
        return ['code' => 0, 'data' => $insertId];
    }

    //校验分类是否存在-通过id
    static public function checkClass($id)
    {
        $checkInfo = MaterielClassModel::where('id', $id)->where('delete_flag', 0)->first();

        if(empty($checkInfo)) {
            return false;
        }
        else {
            return true;
        }
    }

    //检查下一级分类有无
    static public function checkNext($id)
    {
        $info = MaterielClassModel::where('id', $id)->where('delete_flag', 0)->first();

        if($info['parent_id'] == 0) {
            if(!empty(MaterielClassModel::where(['parent_id' => $id, 'delete_flag' => 0])->first())) {
                return 1;
            }
            else {
                return 0;
            }
        }
        else {
            //该二级分类下是否存在未删除的
            if(!empty(MaterielsTypeModel::where(['materiel_class_id' => $id, 'delete_flag' => 0])->first())) {
                return 2;
            }
            else {
                return 0;
            }
        }
    }

    //编辑商品分类信息
    static public function edit($data)
    {
        $info = MaterielClassModel::where('id', $data['id'])->where('delete_flag', 0)->first();

        if(empty($info)) {
            return 0;
        }

        //type->0:一级分类;1:二级分类;
        if($data['type']) {
            if($info['parent_id'] == 0) {
                return 1;
            }

            if($data['parent_id'] == 0) {
                return 2;
            }

            $checkNoInfo = MaterielClassModel::where([
                'parent_id' => $data['parent_id'],
                'class_no' => $data['class_no'],
                'main_id' => $data['main_id'],
                'delete_flag' => 0,
            ])
                ->where('id', '!=', $data['id'])
                ->first();

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  $data['parent_id'],
                'class_name' => $data['class_name'],
                'main_id' => $data['main_id'],
                'delete_flag' => 0
            ])
                ->where('id', '!=', $data['id'])
                ->first();

            if(!empty($checkNoInfo)) {
                return 3;
            }

            if(!empty($checkNameInfo)) {
                return 4;
            }
        }
        else {
            if($info['parent_id'] != 0) {
                return 1;
            }

            $checkNoInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_no' => $data['class_no'],
                'main_id' => $data['main_id'],
                'delete_flag' => 0,
            ])
                ->where('id', '!=', $data['id'])
                ->first();

            if(!empty($checkNoInfo)) {
                return 3;
            }

            $checkNameInfo = MaterielClassModel::where([
                'parent_id' =>  0,
                'class_name' => $data['class_name'],
                'main_id' => $data['main_id'],
                'delete_flag' => 0,
            ])
                ->where('id', '!=', $data['id'])
                ->first();

            if(!empty($checkNameInfo)) {
                return 4;
            }
        }

        unset($data['type']);

        MaterielClassModel::where('id', $data['id'])->update($data);
        return 5;
    }
}
